C++プログラムの壮大な劇場において、オブジェクトは俳優に似ています。一部は全編を通じて舞台に残りますが、大多数の—— ローカルオブジェクト——は一場面だけ現れて永久に消える儚い存在です。本レッスンでは、オブジェクトの 可視性 (スコープ) とその 存在 (ライフタイム)の根本的な違いを確立します。
1. 語彙的スコープと実行時の寿命
名前に対する スコープ はコンパイル時における性質であり、名前が使用可能なプログラムテキストの領域を指します。逆に、 寿命 は実行時における性質であり、オブジェクトが物理的なメモリアドレスを占有する期間を意味します。
2. 自動オブジェクト
ブロックが実行中だけ存在するオブジェクトは 自動オブジェクトです。制御が定義部を通過したとき(int n = 0;)で作成され、閉じ括弧(})に到達したときに破棄されます。パラメータは引数によって初期化されるローカル変数として機能します。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
When is an automatic object's memory typically reclaimed?
When the program finishes execution.
When the enclosing block (braces) terminates.
When the object is assigned a new value.
When the compiler optimizes the code.
✅ Correct!
Correct! Automatic objects are 'popped' from the stack the moment the function or block they are defined in ends.❌ Incorrect
The lifetime of an automatic object is strictly tied to the execution of the block where it is defined.QUESTION 2
True or False: A function's parameters have a lifetime that spans the entire program.
True
False
✅ Correct!
False is correct. Parameters are local variables; they are created when the function is called and destroyed when it returns.❌ Incorrect
Parameters are ephemeral. They only exist while the function is actively executing.QUESTION 3
Which code snippet demonstrates the creation of an automatic object?
static int count = 0;int val = 5; (inside a function)extern int globalVar;#define MAX 100✅ Correct!
Regular variables defined inside a function without the 'static' keyword are automatic objects.❌ Incorrect
'static' objects have a lifetime that persists for the entire program execution, not just the block.QUESTION 4
In the context of local scope, what does 'lexical' refer to?
The speed of the program execution.
The memory address on the stack.
The physical region of the source code text.
The dictionary of keywords in C++.
✅ Correct!
Lexical scope refers to the spatial region in the code file where a name is recognized.❌ Incorrect
Lexical scope is a compile-time property related to the 'text' of the code, not the runtime execution.QUESTION 5
What is the primary benefit of automatic objects?
They allow variables to be accessed from any function.
They ensure memory efficiency by reclaiming space automatically.
They prevent the use of headers.
They increase the binary size of the program.
✅ Correct!
By automatically cleaning up memory when a block ends, C++ avoids the overhead of manual management for temporary variables.❌ Incorrect
Automatic objects are local; their benefit is memory safety and isolation within functions.Deep Dive: Local Variable Architecture
Analysis of Scope and Writing Requirements
You are auditing a function designed to process string inputs. You must distinguish between the placeholders (parameters) and the actual data passed (arguments), while ensuring the memory for local processing doesn't leak. Consider the following definitions:
- Parameter: Variable in function signature.
- Argument: Value passed during call.
- Local: Defined in block.
- Static Local: Local scope, global lifetime.
Q
1. [Short Answer] What is the difference between a parameter and an argument? (Minimum 50 words required)
Solution:
A parameter is a formal variable declared in the function's header that acts as a placeholder for incoming data. In contrast, an argument is the actual value, variable, or expression supplied to the function during a call. When a function is invoked, the parameters are initialized using the values of the arguments. This distinction is vital because parameters are local automatic objects that exist only within the function's lifetime, whereas the arguments exist in the caller's scope and may persist long after the function returns. Understanding this helps prevent confusion regarding data ownership and side effects.
A parameter is a formal variable declared in the function's header that acts as a placeholder for incoming data. In contrast, an argument is the actual value, variable, or expression supplied to the function during a call. When a function is invoked, the parameters are initialized using the values of the arguments. This distinction is vital because parameters are local automatic objects that exist only within the function's lifetime, whereas the arguments exist in the caller's scope and may persist long after the function returns. Understanding this helps prevent confusion regarding data ownership and side effects.
Q
2. [Short Answer] Explain the differences between a parameter, a local variable, and a local static variable. Give an example of a function in which each might be useful.
Solution:
A parameter is initialized by arguments at the call site and represents input data. A local variable is defined inside a block for temporary processing and is destroyed upon block exit. A local static variable is defined in a block (local scope) but its lifetime persists across function calls (global lifetime). Example: In a `logTransaction(double amount)` function, `amount` is a parameter representing the specific data. `double tax = amount * 0.1;` is a local variable used for a one-time calculation. `static int callCount = 0;` is a local static variable used to track how many times the function has been executed across the entire program session.
A parameter is initialized by arguments at the call site and represents input data. A local variable is defined inside a block for temporary processing and is destroyed upon block exit. A local static variable is defined in a block (local scope) but its lifetime persists across function calls (global lifetime). Example: In a `logTransaction(double amount)` function, `amount` is a parameter representing the specific data. `double tax = amount * 0.1;` is a local variable used for a one-time calculation. `static int callCount = 0;` is a local static variable used to track how many times the function has been executed across the entire program session.
Q
3. [Writing Task] Write a main function that takes two arguments. Concatenate the supplied arguments and print the resulting string. (Minimum 30 words required)
Solution:
cpp int main(int argc, char* argv[]) { if (argc < 3) return 1; // We must check if two arguments were actually provided via the command line. std::string result = std::string(argv[1]) + std::string(argv[2]); std::cout << result << std::endl; return 0; } This implementation utilizes the `argc` parameter to verify that the user provided at least two arguments before attempting to concatenate and print the combined string result.
cpp int main(int argc, char* argv[]) { if (argc < 3) return 1; // We must check if two arguments were actually provided via the command line. std::string result = std::string(argv[1]) + std::string(argv[2]); std::cout << result << std::endl; return 0; } This implementation utilizes the `argc` parameter to verify that the user provided at least two arguments before attempting to concatenate and print the combined string result.
Q
4. [Writing Task] Exercise 6.22: Write a function to swap two int pointers.
Solution:
To swap the actual addresses stored in two pointers, we must pass the pointers by reference: cpp void swapPointers(int* &p1, int* &p2) { int* temp = p1; p1 = p2; p2 = temp; } By using a reference to a pointer (`int* &`), the function can modify the local pointers in the calling scope rather than just swapping local copies of the addresses.
To swap the actual addresses stored in two pointers, we must pass the pointers by reference: cpp void swapPointers(int* &p1, int* &p2) { int* temp = p1; p1 = p2; p2 = temp; } By using a reference to a pointer (`int* &`), the function can modify the local pointers in the calling scope rather than just swapping local copies of the addresses.